import * as SERVICE from '../utils/service'
import gcoord from 'gcoord'
import Map from 'ol/Map'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import OSM from 'ol/source/OSM'
import View from 'ol/View'
import { defaults } from 'ol/control.js'
import { defaults as defaultInteractions } from 'ol/interaction'
import { fromLonLat } from 'ol/proj'
import XYZ from 'ol/source/XYZ'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import VectorSource from 'ol/source/Vector'
import { Icon, Text, Stroke, Fill, Style } from 'ol/style'

//定义全局变量
export const staticParam = {
    olmap: undefined,
    layers: [],
    tempLayers: [],
}

//定义地图视图中心点
const view = new View({
    // 113.274063, 35.193959
    //113.24315696502676,35.21484481827645
    center: fromLonLat([113.241823, 35.215892]),
    zoom: 10,
    projection: 'EPSG:3857',
})

//定义地图控件
const controls = new defaults({
    pinchRotate: false, // 移动端禁止地图旋转
    attribution: false,
    rotate: false,
    zoom: false,
})

//定义全局方法
/**
 * 初始化openlayers地图
 * @param {Openlayers地图容器的id值} _mapid
 */
export const initOlMap = (_mapid) => {
    var map = new Map({
        interactions: defaultInteractions({
            pinchRotate: false, // 移动端禁止地图旋转
        }),
        layers: [
            //定义图层
            // new TileLayer({
            //     source: new OSM(),
            // }),
            new TileLayer({
                className: 'maptiles',
                source: new XYZ({
                    // 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}&scl=1&ltype=2',
                    url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                    // url: 'http://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                    // url: 'http://192.168.124.70/{z}/{x}/{y}.jpg',
                    wrapX: true,
                }),
                visible: true,
            }),
            new TileLayer({
                //影像底图
                className: 'sat',
                source: new XYZ({
                    // 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}&scl=1&ltype=2',
                    // url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                    url: 'http://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                    // url: 'http://192.168.124.70/{z}/{x}/{y}.jpg',
                    wrapX: true,
                }),
                visible: false,
            }),
        ],
        target: _mapid, //dom容器的id值
        view: view,
        controls: controls,
    })
    map.on('moveend', (event) => {
            var zoom = map.getView().getZoom() //获取当前地图的缩放级别
            console.log(zoom)
        })
        //变量引用
    staticParam.olmap = map
    console.log(staticParam.olmap)
        //初始化所有图层
    initAllLayers(staticParam.olmap)
}

/**
 *  * 添加临时图层
 * @param {地图实例} _map
 * @param {经度} _lng
 * @param {纬度} _lat
 * @param {关键词} _value
 */
export const addTempLayers = (_map, _lng, _lat, _value) => {
    SERVICE.getServicePointsByBuffer(_lng, _lat).then((res) => {
        let data = res.data
        console.log(data)
            //要素层数组
        let features = []
            //遍历结果集
        let len = data.length - 1
        console.log(_value)
        while (len >= 0) {
            if (data[len].name.includes(_value)) {
                console.log('添加')
                features.push(
                    getFeatureByAttrs(
                        data[len].name,
                        'temp',
                        data[len].lon,
                        data[len].lat,
                        'locationmarker'
                    )
                )
            }
            len--
        }
        //创建标记图层
        let tempMarkers = new VectorLayer({
            className: 'supermarket-layer',
            source: new VectorSource({
                features: features,
            }),
            visible: true,
        })
        staticParam.tempLayers.push(tempMarkers)
        _map.addLayer(tempMarkers)
    })
}

/**
 * 初始化所有图层
 * @param {地图实例} _map
 */
export const initAllLayers = (_map) => {
    // let supermarketIcon = require('../../static/imgs/supermarket.png'),
    //     hospitalIcon = require('../../static/imgs/hospital.png'),
    //     sceneryIcon = require('../../static/imgs/sceneryIcon.png')
    //初始化超市点
    SERVICE.getSuperMarketList(0, 0).then((res) => {
            let data = res.data
            let features = []
            let len = data.length - 1
            while (len >= 0) {
                features.push(
                    getFeatureByAttrs(
                        data[len].name,
                        data[len].type,
                        data[len].lon,
                        data[len].lat,
                        'supermarket'
                    )
                )
                len--
            }
            let superMarketLayer = new VectorLayer({
                className: 'supermarket-layer',
                source: new VectorSource({
                    features: features,
                }),
                visible: false,
            })
            staticParam.layers.push(superMarketLayer)
            _map.addLayer(superMarketLayer)
        })
        //初始化医疗点
    SERVICE.getHospitalList(0, 0).then((res) => {
            let data = res.data
            let features = []
            let len = data.length - 1
            while (len >= 0) {
                features.push(
                    getFeatureByAttrs(
                        data[len].name,
                        data[len].type,
                        data[len].lon,
                        data[len].lat,
                        'hospital'
                    )
                )
                len--
            }
            let hospitalLayer = new VectorLayer({
                className: 'hospital-layer',
                source: new VectorSource({
                    features: features,
                }),
                visible: false,
            })
            staticParam.layers.push(hospitalLayer)
            _map.addLayer(hospitalLayer)
        })
        //初始化休闲点
    SERVICE.getSceneryPointList(0, 0).then((res) => {
        let data = res.data
        let features = []
        let len = data.length - 1
        while (len >= 0) {
            features.push(
                getFeatureByAttrs(
                    data[len].name,
                    data[len].type,
                    data[len].lon,
                    data[len].lat,
                    'sceneryIcon'
                )
            )
            len--
        }
        let sceneryLayer = new VectorLayer({
            className: 'scenery-layer',
            source: new VectorSource({
                features: features,
            }),
            visible: false,
        })
        staticParam.layers.push(sceneryLayer)
        _map.addLayer(sceneryLayer)
    })
}

/**
 * 根据className属性获取Layer实例
 * @param {VectorLayer的className属性值} _className
 * @returns ol/Layer实例
 */
export const setLayerVisibleByClassName = (_className) => {
    let len = staticParam.layers.length - 1
    if (_className) {
        while (len >= 0) {
            // console.log(staticParam.layers[len])
            if (staticParam.layers[len].className_ == _className) {
                staticParam.layers[len].values_.visible = true
            } else {
                staticParam.layers[len].values_.visible = false
            }
            len--
        }
    }
    while (len >= 0) {
        // console.log(staticParam.layers[len])
        staticParam.layers[len].values_.visible = false
        len--
    }
}

/**
 * @param {名称} _name
 * @param {类型} _type
 * @param {经度} _lon
 * @param {纬度} _lat
 * @param {图标资源} _src
 */
export function getFeatureByAttrs(_name, _type, _lon, _lat, _src) {
    let feature = new Feature({
        geometry: new Point(
            //百度坐标系转高德坐标系
            fromLonLat(gcoord.transform([_lon, _lat], gcoord.BD09, gcoord.GCJ02))
        ),
        name: _name,
        type: _type,
    })
    let style = new Style({
        image: new Icon({
            anchor: [0.5, 0.5],
            crossOrigin: 'anonymous',
            src: require('../../static/imgs/' + `${_src}` + '.png'),
            scale: 0.2,
        }),
        // text: new Text({
        //     text: _name,
        //     backgroundFill: new Fill({
        //         color: '#ccc',
        //     }),
        // }),
        text: new Text({
            font: '13px Microsoft YaHei',
            text: _name,
            textAlign: 'center',
            textBaseline: 'top',
            offsetX: 0,
            offsetY: 10,
            backgroundFill: new Fill({
                color: '#e0ffff',
            }),
            padding: [0, 0, 0, 0],
            fill: new Fill({
                color: '#708090',
            }),
            scale: [1, 1],
        }),
    })
    feature.setStyle(style)
    return feature
}

/**
 * 根据经纬度坐标值创建标注点
 * @param {经度} _lng
 * @param {纬度} _lat
 */
export function createMarker(_lnglat) {
    // fromLonLat(gcoord.transform([_lng, _lat], gcoord.WGS84, gcoord.GCJ02))
    var iconFeature = new Feature({
        geometry: new Point(
            fromLonLat(_lnglat)
            // fromLonLat(gcoord.transform(_lnglat, gcoord.WGS84, gcoord.GCJ02))
        ),
        name: 'Null Island',
    })

    var iconStyle = new Style({
        image: new Icon({
            anchor: [0.5, 0.5],
            // anchorXUnits: 'fraction',
            // anchorYUnits: 'pixels',
            crossOrigin: 'anonymous',
            src: require('../../static/imgs/locationmarker.png'),
            // imgSize: [12, 12],
            // opacity: 0.5,//透明度
            scale: 0.3,
        }),
    })

    iconFeature.setStyle(iconStyle)

    var vectorSource = new VectorSource({
        features: [iconFeature],
    })

    var vectorLayer = new VectorLayer({
        source: vectorSource,
        visible: true,
    })
    staticParam.olmap.addLayer(vectorLayer)
    return vectorLayer
}